package com.xlf.mail;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.jfinal.plugin.activerecord.Page;
import com.xlf.common.model.Email;
import com.xlf.common.model.Factory;
import com.xlf.common.model.Order;

public class SendMail {
	// 收件人邮箱地址
	private String to;
	// 发件人邮箱地址
	private String from;
	// SMTP服务器地址
	private String smtpServer;
	// 登录SMTP服务器的用户名
	private String username;
	// 登录SMTP服务器的密码
	private String password;
	// 邮件主题
	private String subject;
	// 邮件正文
	private String content;
	// 是否开启
	private String isstart;
	// 记录所有附件文件的集合
	List<String> attachments = new ArrayList<String>();

	// 无参数的构造器
	public SendMail() {
	}

	public SendMail(String to, String from, String smtpServer, String username,
			String password, String subject, String content,String isstart) {
		this.to = to;
		this.from = from;
		this.smtpServer = smtpServer;
		this.username = username;
		this.password = password;
		this.subject = subject;
		this.content = content;
		this.isstart = isstart;
	}

	// to属性的setter方法
	public void setTo(String to) {
		this.to = to;
	}

	// from属性的setter方法
	public void setFrom(String from) {
		this.from = from;
	}

	// smtpServer属性的setter方法
	public void setSmtpServer(String smtpServer) {
		this.smtpServer = smtpServer;
	}

	// username属性的setter方法
	public void setUsername(String username) {
		this.username = username;
	}

	// password属性的setter方法
	public void setPassword(String password) {
		this.password = password;
	}

	// subject属性的setter方法
	public void setSubject(String subject) {
		this.subject = subject;
	}

	// content属性的setter方法
	public void setContent(String content) {
		this.content = content;
	}

	public String getIsstart() {
		return isstart;
	}

	public void setIsstart(String isstart) {
		this.isstart = isstart;
	}

	// 把邮件主题转换为中文
	public String transferChinese(String strText) {
		try {
			strText = MimeUtility.encodeText(new String(strText.getBytes(),
					"GB2312"), "GB2312", "B");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strText;
	}

	// 增加附件，将附件文件名添加的List集合中
	public void attachfile(String fname) {
		attachments.add(fname);
	}

	// 发送邮件
	public boolean send(Order order) {
		
		Page<Factory> pageRecord = Factory.dao.exeFactoryNameByOid((String) order.get("o_id"));
		String factoryName = "";
		if(pageRecord.getList().size() != 0){
			factoryName = pageRecord.getList().get(0).get("name");
		}
		// by zyk id 时间 订单号 客户姓名 厂家名称 邮箱地址 发送结果 异常描述
		Email ec = new Email();
		ec.set("createtime",new Date());
		ec.set("o_id", order.get("o_id"));
		ec.set("custername", order.get("custerName"));
		ec.set("factoryname", factoryName);
		ec.set("email", MailProperties.getReceive());
		
		// 创建邮件Session所需的Properties对象
		Properties props = new Properties();
		props.put("mail.smtp.host", MailProperties.getMailserver());
		props.put("mail.smtp.auth", "true");
		// 创建Session对象
		Session session = Session.getDefaultInstance(props
		// 以匿名内部类的形式创建登录服务器的认证对象
				, new Authenticator() {
					public PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(MailProperties.getUsername(), MailProperties.getPassword());
					}
				});
		try {
			// 构造MimeMessage并设置相关属性值
			MimeMessage msg = new MimeMessage(session);
			// 设置发件人
			msg.setFrom(new InternetAddress(MailProperties.getSend()));
			// 设置收件人
			InternetAddress[] addresses = { new InternetAddress(MailProperties.getReceive()) };
			msg.setRecipients(Message.RecipientType.TO, addresses);
			// 设置邮件主题
			subject = transferChinese(MailProperties.getMailtitle());
			msg.setSubject(subject);
			// 构造Multipart
			Multipart mp = new MimeMultipart();
			// 向Multipart添加正文
			MimeBodyPart mbpContent = new MimeBodyPart();
			// by zyk 此处读取文件send.txt内容
			// mbpContent.setText(content);
			String sendTxt = getFileContent();
			mbpContent.setText(sendTxt);
			
			// 将BodyPart添加到MultiPart中
			mp.addBodyPart(mbpContent);
			// 向Multipart添加附件
			// 遍历附件列表，将所有文件添加到邮件消息里
			// for (String efile : attachments) {
			// MimeBodyPart mbpFile = new MimeBodyPart();
			// // 以文件名创建FileDataSource对象
			// FileDataSource fds = new FileDataSource(efile);
			// // 处理附件
			// mbpFile.setDataHandler(new DataHandler(fds));
			// mbpFile.setFileName(fds.getName());
			// // 将BodyPart添加到MultiPart中
			// mp.addBodyPart(mbpFile);
			// }
			// // 清空附件列表
			// attachments.clear();
			// 向Multipart添加MimeMessage
			msg.setContent(mp);
			// 设置发送日期
			msg.setSentDate(new Date());
			// 发送邮件
			Transport.send(msg);
			
		
			ec.set("result", "成功");
			ec.save();
			// 保存邮件记录
		} catch (MessagingException mex) {
			ec.set("result", "失败");
			ec.set("exceptiondesc", "邮件服务器超时或其他原因");
			ec.save();
			// 失败保存记录
			return false;
		}
		return true;
	}

	public String getFileContent() {
		String FileName = "./config/send.txt";
		File myFile = new File(FileName);
		if (!myFile.exists()) {
			System.err.println("Can't Find " + FileName);
		}
		String str = "";
		StringBuilder sb = new StringBuilder();
		
		try {
			BufferedReader in = new BufferedReader(new FileReader(myFile));
			while((str = in.readLine()) != null){
				sb.append(str + "\n");
			}
			in.close();
		} catch (IOException e) {
			e.getStackTrace();
		}
		return sb.toString();
	}

	public List<String> getAttachments() {
		return attachments;
	}

	public void setAttachments(List<String> attachments) {
		this.attachments = attachments;
	}

	public String getTo() {
		return to;
	}

	public String getFrom() {
		return from;
	}

	public String getSmtpServer() {
		return smtpServer;
	}

	public String getUsername() {
		return username;
	}

	public String getPassword() {
		return password;
	}

	public String getSubject() {
		return subject;
	}

	public String getContent() {
		return content;
	}

	public static void main(String[] args) {
		SendMail sendMail = new SendMail();
		sendMail.setSmtpServer("smtp.163.com");
		// 此处设置登录的用户名
		sendMail.setUsername("ccyuankai@163.com");
		// 此处设置登录的密码
		sendMail.setPassword("198001055");
		// 设置收件人的地址
		sendMail.setTo("12215380@qq.com");
		// 设置发送人地址
		sendMail.setFrom("ccyuankai@163.com");
		// 设置标题
		sendMail.setSubject("测试邮件标题！");
		// 设置内容
		sendMail.setContent("你好这是一个测试邮件！");
		// 粘贴附件
		// sendMail.attachfile("C:/Login6 (1).jpg");
		sendMail.attachfile("");
//		if (sendMail.send()) {
//			System.out.println("---邮件发送成功---");
//		}
	}
}